<script setup lang="ts">
import { useRole } from "./utils/hook";
import { ref, computed, nextTick, onMounted } from "vue";
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import {
  delay,
  subBefore,
  deviceDetection,
  useResizeObserver
} from "@pureadmin/utils";
import {
  getVideoList,
  type VideoListParams,
  type VideoListResponse
} from "@/api/material";
import type { TableColumns } from "@pureadmin/table";

// import Database from "@iconify-icons/ri/database-2-line";
// import More from "@iconify-icons/ep/more-filled";
import Delete from "@iconify-icons/ep/delete";
import EditPen from "@iconify-icons/ep/edit-pen";
import Refresh from "@iconify-icons/ep/refresh";
import Menu from "@iconify-icons/ep/menu";
import AddFill from "@iconify-icons/ri/add-circle-line";
import Close from "@iconify-icons/ep/close";
import Check from "@iconify-icons/ep/check";

defineOptions({
  name: "MaterialManagement"
});

const iconClass = computed(() => {
  return [
    "w-[22px]",
    "h-[22px]",
    "flex",
    "justify-center",
    "items-center",
    "outline-none",
    "rounded-[4px]",
    "cursor-pointer",
    "transition-colors",
    "hover:bg-[#0000000f]",
    "dark:hover:bg-[#ffffff1f]",
    "dark:hover:text-[#ffffffd9]"
  ];
});

const treeRef = ref();
const formRef = ref();
const tableRef = ref();
const contentRef = ref();
const treeHeight = ref();

const form = ref({
  name: "",
  project: "",
  product: "",
  editor: "",
  director: "",
  videoMode: "",
  state: undefined,
  adAccountId: "",
  dateRange: []
});

const pagination = ref({
  total: 0,
  pageSize: 10,
  currentPage: 1,
  pageSizes: [10, 20, 50, 100],
  small: false
});

const columns = ref<TableColumns[]>([
  {
    type: "selection",
    width: 55,
    align: "left",
    hide: false,
    label: "选择"
  },
  {
    label: "素材名称",
    prop: "name",
    width: 180
  },
  {
    label: "素材预览",
    prop: "preview",
    width: 120
  },
  {
    label: "项目",
    prop: "project"
  },
  {
    label: "产品",
    prop: "product"
  },
  {
    label: "编导",
    prop: "editor"
  },
  {
    label: "剪辑",
    prop: "instructor"
  },
  {
    label: "优化师",
    prop: "optimizer"
  },
  {
    label: "消耗(USD)",
    prop: "cost"
  },
  {
    label: "激活",
    prop: "activation"
  },
  {
    label: "付费/加购",
    prop: "payment"
  }
]);

const {
  form: roleForm,
  isShow,
  curRow,
  rowStyle,
  treeData,
  treeProps,
  isLinkage,
  handleMenu,
  handleSave,
  handleDelete,
  filterMethod,
  transformI18n,
  onQueryChanged
} = useRole(treeRef);

// 添加缺失的响应式变量
const treeSearchValue = ref("");
const isExpandAll = ref(false);
const isSelectAll = ref(false);
const loading = ref(false);
const dataList = ref([]);

// 获取视频素材列表数据
const fetchVideoList = async () => {
  loading.value = true;
  try {
    const params: VideoListParams = {
      page: pagination.value.currentPage,
      size: pagination.value.pageSize,
      name: form.value.name,
      videoMode: form.value.videoMode,
      state: form.value.state,
      adAccountId: form.value.adAccountId,
      director: form.value.director,
      editor: form.value.editor
    };

    const { list, total } = await getVideoList(params);
    dataList.value = list;
    pagination.value.total = total;
  } catch (error) {
    console.error("获取视频素材列表失败:", error);
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.value.currentPage = 1;
  fetchVideoList();
};

// 重置表单
const handleResetForm = formEl => {
  if (!formEl) return;
  formEl.resetFields();
  handleSearch();
};

// 处理分页大小变化
const onSizeChange = (val: number) => {
  pagination.value.pageSize = val;
  fetchVideoList();
};

// 处理页码变化
const onCurrentChange = (val: number) => {
  pagination.value.currentPage = val;
  fetchVideoList();
};

const handlePreview = (row: any) => {
  console.log("Preview video:", row.name);
};

// 打开新增素材对话框
const openDialog = () => {
  // TODO: 实现新增素材对话框逻辑
  console.log("Open add material dialog");
};

onMounted(() => {
  fetchVideoList();
  useResizeObserver(contentRef, async () => {
    await nextTick();
    delay(60).then(() => {
      treeHeight.value = parseFloat(
        subBefore(tableRef.value.getTableDoms().tableWrapper.style.height, "px")
      );
    });
  });
});
</script>

<template>
  <div class="main">
    <el-form
      ref="formRef"
      :inline="true"
      :model="form"
      class="search-form w-[99/100] mx-auto bg-white p-[20px]"
    >
      <el-form-item label="项目：" prop="project">
        <el-input
          v-model="form.project"
          placeholder="请选择"
          clearable
          class="!w-[180px]"
        />
      </el-form-item>
      <el-form-item label="产品：" prop="product">
        <el-input
          v-model="form.product"
          placeholder="请选择"
          clearable
          class="!w-[180px]"
        />
      </el-form-item>
      <el-form-item label="剪辑师：" prop="editor">
        <el-select
          v-model="form.editor"
          placeholder="请选择"
          clearable
          class="!w-[180px]"
        />
      </el-form-item>
      <el-form-item label="编导：" prop="director">
        <el-select
          v-model="form.director"
          placeholder="请选择"
          clearable
          class="!w-[180px]"
        />
      </el-form-item>
      <el-form-item label="视频模式：" prop="videoMode">
        <el-select
          v-model="form.videoMode"
          placeholder="请选择"
          clearable
          class="!w-[180px]"
        />
      </el-form-item>
      <el-form-item label="状态：" prop="state">
        <el-select
          v-model="form.state"
          placeholder="请选择"
          clearable
          class="!w-[180px]"
        />
      </el-form-item>
      <el-form-item label="广告账户ID：" prop="adAccountId">
        <el-input
          v-model="form.adAccountId"
          placeholder="请输入"
          clearable
          class="!w-[180px]"
        />
      </el-form-item>
      <el-form-item label="日期：">
        <el-date-picker
          v-model="form.dateRange"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon('ri:search-line')"
          :loading="loading"
          @click="handleSearch"
        >
          搜索
        </el-button>
        <el-button
          :icon="useRenderIcon(Refresh)"
          @click="handleResetForm(formRef)"
        >
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <div ref="contentRef" class="w-[99/100] mx-auto mt-4">
      <PureTableBar
        class="bg-white p-[20px]"
        style="transition: width 220ms cubic-bezier(0.4, 0, 0.2, 1)"
        title="素材管理"
        :columns="columns"
        @refresh="handleSearch"
      >
        <template #buttons>
          <el-button
            type="primary"
            :icon="useRenderIcon(AddFill)"
            @click="openDialog()"
          >
            新增素材
          </el-button>
        </template>
        <pure-table
          ref="tableRef"
          :data="dataList"
          :columns="columns"
          :pagination="pagination"
          :header-cell-style="{
            background: 'var(--el-fill-color-light)',
            color: 'var(--el-text-color-primary)'
          }"
          class="bg-white"
          @page-size-change="onSizeChange"
          @page-current-change="onCurrentChange"
        >
          <template #default="{ size }">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="素材名称" prop="name" width="180" />
            <el-table-column label="素材预览" width="120">
              <template #default="{ row }">
                <el-button
                  class="reset-margin"
                  link
                  type="primary"
                  :size="size"
                  :icon="useRenderIcon('ep:video-play')"
                  @click="handlePreview(row)"
                >
                  预览
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="项目" prop="project" />
            <el-table-column label="产品" prop="product" />
            <el-table-column label="编导" prop="editor" />
            <el-table-column label="剪辑" prop="instructor" />
            <el-table-column label="优化师" prop="optimizer" />
            <el-table-column label="消耗(USD)" prop="cost" />
            <el-table-column label="激活" prop="activation" />
            <el-table-column label="付费/加购" prop="payment" />
          </template>
        </pure-table>
      </PureTableBar>

      <div
        v-if="isShow"
        class="!min-w-[calc(100vw-60vw-268px)] mt-2 px-2 pb-2 bg-bg_color ml-2 overflow-auto"
      >
        <div class="flex justify-between w-full px-3 pt-5 pb-4">
          <div class="flex">
            <span :class="iconClass">
              <IconifyIconOffline
                v-tippy="{
                  content: '关闭'
                }"
                class="dark:text-white"
                width="18px"
                height="18px"
                :icon="Close"
                @click="handleMenu"
              />
            </span>
            <span :class="[iconClass, 'ml-2']">
              <IconifyIconOffline
                v-tippy="{
                  content: '保存菜单权限'
                }"
                class="dark:text-white"
                width="18px"
                height="18px"
                :icon="Check"
                @click="handleSave"
              />
            </span>
          </div>
          <p class="font-bold truncate">
            菜单权限
            {{ `${curRow?.name ? `（${curRow.name}）` : ""}` }}
          </p>
        </div>
        <el-input
          v-model="treeSearchValue"
          placeholder="请输入菜单进行搜索"
          class="mb-1"
          clearable
          @input="onQueryChanged"
        />
        <div class="flex flex-wrap">
          <el-checkbox v-model="isExpandAll" label="展开/折叠" />
          <el-checkbox v-model="isSelectAll" label="全选/全不选" />
          <el-checkbox v-model="isLinkage" label="父子联动" />
        </div>
        <el-tree-v2
          ref="treeRef"
          show-checkbox
          :data="treeData"
          :props="treeProps"
          :height="treeHeight"
          :check-strictly="!isLinkage"
          :filter-method="filterMethod"
        >
          <template #default="{ node }">
            <span>{{ transformI18n(node.label) }}</span>
          </template>
        </el-tree-v2>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}

.main-content {
  margin: 24px 24px 0 !important;
}

.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}

:deep(.el-pagination) {
  justify-content: flex-end;
  margin-right: 20px;
}
</style>
